package display;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

import GJAM.MVC.*;
import GJAM.SAMPLE.Calculator.CalculatorModel;
import GJAM.SAMPLE.Calculator.CalculatorView;
import GJAM.SAMPLE.Calculator.SplashScreenView;

public class CalculatorControllerMidlet extends Controller {

    private Display display;
    private Command exitCommand;
    private Command continueCommand;
    private Command calculateCommand;
    private CalculatorModel model;
    private CalculatorView calculatorView;
    private SplashScreenView splashScreenView;

    public CalculatorControllerMidlet() {
        display = Display.getDisplay(this);
        
        display.setCurrent(getSplashScreenView());
    }

    public void commandAction(Command command, Displayable displayItem) {
        if (command == continueCommand){
            display.setCurrent(getCalculatorView());
        }
        
        if (command == calculateCommand) {
            model.Calculate(calculatorView.getOperand1(), calculatorView.getOperator(), calculatorView.getOperand2());
            updateViews();
        }

        if (command == exitCommand) {
            exitApp();
        }
    }
    
    private CalculatorView getCalculatorView() {
        if (calculatorView == null) {
            calculatorView = new CalculatorView(getModel(), display);
            calculatorView.addCommand(getExitCommand());
            calculatorView.addCommand(getCalculateCommand());
            calculatorView.setCommandListener(this);
            register(calculatorView);
        }
        return calculatorView;
    }
    
    private SplashScreenView getSplashScreenView(){
       if(splashScreenView == null){
          splashScreenView = new SplashScreenView(null, display);
          splashScreenView.addCommand(getContinueCommand());
          splashScreenView.setCommandListener(this);
       }
       
       return splashScreenView;
    }

    private CalculatorModel getModel() {
        if (model == null) {
            model = new CalculatorModel();
        }

        return model;
    }

    private Command getExitCommand() {
        if (exitCommand == null) {
            exitCommand = new Command("Exit", Command.EXIT, 60);
        }

        return exitCommand;
    }
    
    private Command getContinueCommand() {
        if (continueCommand == null) {
            continueCommand = new Command("Continue", Command.ITEM, 60);
        }

        return continueCommand;
    }

    private Command getCalculateCommand() {
        if (calculateCommand == null) {
            calculateCommand = new Command("Calculate", Command.ITEM, 60);
        }

        return calculateCommand;
    }

    public void startApp() {
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        display.setCurrent((Displayable) null);
    }

    public void exitApp() {
        destroyApp(false);
        notifyDestroyed();
    }
}
